package cc.vv.party.config

import cc.vv.party.exception.BizException
import cc.vv.party.quartz.QuartzJobFactory
import org.springframework.beans.factory.config.PropertiesFactoryBean
import org.springframework.context.annotation.Bean
import org.springframework.core.io.ClassPathResource
import org.springframework.scheduling.quartz.SchedulerFactoryBean
import org.quartz.spi.JobFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.ApplicationContext
import java.util.*


/**
 * @version 1.0.0
 * @author: Gyb
 * @date 2018-11-01
 * @description
 **/
class QuartzClusterConfig(@Value("\${quartz.properties-file}") val propertiesPath: String) {

    @Bean
    fun jobFactory(applicationContext: ApplicationContext): JobFactory {
        val jobFactory = QuartzJobFactory()
        jobFactory.setApplicationContext(applicationContext)
        return jobFactory
    }

    @Bean
    fun schedulerFactoryBean(jobFactory: JobFactory): SchedulerFactoryBean {
        val schedulerFactoryBean = SchedulerFactoryBean()
        schedulerFactoryBean.setJobFactory(jobFactory)
        schedulerFactoryBean.setStartupDelay(20)
        //用于quartz集群,加载quartz数据源配置
        schedulerFactoryBean.setQuartzProperties(quartzProperties())
        return schedulerFactoryBean
    }

    private fun quartzProperties(): Properties {
        val factoryBean = PropertiesFactoryBean()
        factoryBean.setLocation(ClassPathResource(propertiesPath))
        try {
            factoryBean.afterPropertiesSet()
            return factoryBean.getObject()!!
        } catch (e: Exception) {
            throw BizException("Quartz 初始化失败")
        }
    }

}